package com.ruhaly.common_lib.base;


import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

import com.ruhaly.common_lib.R;
import com.trello.rxlifecycle.components.support.RxDialogFragment;

import static com.ruhaly.common_lib.utils.L.makeLogTag;


public class ProgressDialog extends RxDialogFragment {
    @SuppressWarnings("unused")
    private static final String TAG = makeLogTag(ProgressDialog.class);
    private static final String PARAM_DESC = "_desc";
    public static final String PROGRESS_TAG = "_progress";


    public ProgressDialog(int resId) {
        Bundle b = new Bundle();
        b.putInt(PARAM_DESC, resId);
        setArguments(b);
    }

    public ProgressDialog() {
        Bundle b = new Bundle();
        b.putInt(PARAM_DESC, R.string.common_blocking_please_wait);
        setArguments(b);
    }

    public void display(FragmentManager fragmentManager) {
        Fragment fragment = fragmentManager.findFragmentByTag(PROGRESS_TAG);
        if (null == fragment || !fragment.isAdded()) {
            show(fragmentManager, PROGRESS_TAG);
            //after transaction you must call the executePendingTransactions
            fragmentManager.executePendingTransactions();
        }
    }

    public void dismiss(FragmentManager fragmentManager) {
        Fragment fragment = fragmentManager.findFragmentByTag(PROGRESS_TAG);
        if (fragment instanceof ProgressDialog) {
            ((ProgressDialog) fragment).dismiss();
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        android.app.ProgressDialog pd = new android.app.ProgressDialog(getActivity());
        int resId = getArguments().getInt(PARAM_DESC, 0);
        pd.setMessage(getString(resId == 0 ? R.string.common_blocking_please_wait : resId));
        return pd;
    }
}
